package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.article.dto.ArticleInfoDto;
import com.itheima.article.feign.ApArticleFeign;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApArticle;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.pojo.ApArticleContent;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.pojo.Result;
import com.itheima.common.pojo.VerifyMessage;
import com.itheima.common.utils.RequestContext;
import com.itheima.wemedia.dto.ContentNode;
import com.itheima.wemedia.dto.WmNewsDtoSave;
import com.itheima.wemedia.mapper.WmNewsMapper;
import com.itheima.wemedia.pojo.WmNews;
import com.itheima.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author czh
 * @since 2021-08-20
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Autowired
    private AdChannelFeign adChannelFeign;

    @Autowired
    private ApArticleFeign apArticleFeign;


    /**
     * 监听风控结果，判断是否同步
     * @param map
     */
    @Override
    public void autoVerify(Map<String, Object> map) {
        //得到文章id
        Integer attach =  Integer.parseInt(map.get("attach").toString());
        //得到结果
        boolean result = (boolean) map.get("result");
        //得到该文章
        WmNews wmNews = wmNewsMapper.selectById(attach);
        if (result){
            //文章没问题,状态可以改为9，并且同步到article中
            wmNews.setStatus(9);
            //判断是否发布
            if (wmNews.getPublishTime()!=null && wmNews.getPublishTime().getSecond() > LocalDateTime.now().getSecond()){
                wmNews.setStatus(8);
            }

        }else {
            //文章有问题，状态改为人工审核
            wmNews.setStatus(3);
        }




        if (wmNews.getStatus() == 9) {
            /***
             * 创建   ArticleDto
             */
            ArticleInfoDto dto = new ArticleInfoDto();
            ApArticle apArticle = new ApArticle();
            //根据用户id查询用户
            Result<ApAuthor> apAuthorResult = apAuthorFeign.getByUserId(wmNews.getUserId());
            if (apAuthorResult != null && apAuthorResult.getData() != null){
                apArticle.setAuthorId(apAuthorResult.getData().getId()); //文章作者id
                apArticle.setAuthorName(apAuthorResult.getData().getName()); //文章作者昵称

            }
            Result<AdChannel> adChannelResult = adChannelFeign.findById(wmNews.getChannelId());
            System.out.println(adChannelResult);
            if (adChannelResult.getData()!=null && adChannelResult.getData().getName()!=null){
                apArticle.setChannelId(wmNews.getChannelId());
                apArticle.setChannelName(adChannelResult.getData().getName()); //频道名称
            }

            if (wmNews.getArticleId() != null){
                apArticle.setId(wmNews.getArticleId());
            }
            apArticle.setTitle(wmNews.getTitle());

            apArticle.setLayout(wmNews.getType());//文章布局，无图，单图
            apArticle.setFlag(0);
            apArticle.setImages(wmNews.getImages());
            apArticle.setLabels(wmNews.getLabels());//标签
            if (wmNews.getPublishTime()!=null){
                apArticle.setPublishTime(wmNews.getPublishTime());
            }
            apArticle.setSyncStatus(wmNews.getStatus());
            apArticle.setLikes(0);
            apArticle.setCollection(0);
            apArticle.setComment(0);
            apArticle.setViews(0);
            dto.setApArticle(apArticle);

            /***
             * 创建 apArticleConfig
             */
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setIsDown(0);
            apArticleConfig.setIsDelete(0);
            dto.setApArticleConfig(apArticleConfig);

            /**
             * 创建articleContent
             */
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setContent(wmNews.getContent());
            dto.setApArticleContent(articleContent);

            //设置作者id
            Result<ApArticle> apArticleResult = apArticleFeign.save(dto);
            Long apArticleId = apArticleResult.getData().getId();
            wmNews.setArticleId(apArticleId);

        }
        wmNewsMapper.updateById(wmNews);

    }


    /**
     * 保存文章,修改文章
     *
     * @param dtoSave
     */
    @Override
    public void insert(WmNewsDtoSave dtoSave) {
        //构建添加的对象
        WmNews wmNews = new WmNews();
        //将dtoSave转为wmNews
        BeanUtils.copyProperties(dtoSave, wmNews);
        //得到用户id
        wmNews.setUserId(RequestContext.getNodeValue("apUserId"));
        //设置文本
        wmNews.setContent(JSON.toJSONString(dtoSave.getContent()));
        //判断图片类型，
        if (dtoSave.getType() == -1) {
            //如果是自动的话，就去上面文本自动拿去
            fetchImage(dtoSave);
        }
        //判断是否有图片，有的话格式转换
        if (dtoSave.getImages() != null && dtoSave.getImages().size() > 0) {
            String images = dtoSave.getImages().toString().substring(1, dtoSave.getImages().toString().length() - 1).replace(" ", "");
            wmNews.setImages(images);
        }
        //设置当前时间
        wmNews.setCreatedTime(LocalDateTime.now());
        //判断是不是草稿
        if (dtoSave.getStatus() == 1) {
            //设置提交时间
            wmNews.setSubmitedTime(LocalDateTime.now());
        }
        if (dtoSave.getId() != null) {
            //修改
            wmNews.setCreatedTime(null);
            wmNewsMapper.updateById(wmNews);
        } else {
            //添加
            wmNewsMapper.insert(wmNews);
        }

        VerifyMessage message = new VerifyMessage(wmNews.getContent(),"wmnews_save_queue",String.valueOf(wmNews.getId()));
        kafkaTemplate.send("checkfortext",JSON.toJSONString(message));
    }


    /**
     * 根据id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public WmNewsDtoSave findById(Integer id) {

        WmNews wmNews = wmNewsMapper.selectById(id);

        if (wmNews != null){
            WmNewsDtoSave dtoSave = new WmNewsDtoSave();

            BeanUtils.copyProperties(wmNews,dtoSave);
            dtoSave.setId(wmNews.getId());
            dtoSave.setTitle(wmNews.getTitle());
            //解析文本转为list
            List<ContentNode> contentNodes = JSON.parseArray(wmNews.getContent(), ContentNode.class);
            dtoSave.setContent(contentNodes);
            //图片转为list
            String[] images = wmNews.getImages().split(",");
            List<String> list = Arrays.asList(images);
            dtoSave.setImages(list);


            return dtoSave;

        }

        return null;
    }

    /**
     * 根据id删除文章
     *
     * @param id
     * @return
     */
    @Override
    public int deleteById(Serializable id) {
        //根据id删除 文章
        int i = wmNewsMapper.deleteNewById(id);

        return i;
    }


    /**
     * 提取封面的图片
     */
    public void fetchImage(WmNewsDtoSave dtoSave) {
        //得到文本内容
        List<ContentNode> contents = dtoSave.getContent();
        //创建List接受图片地址
        List<String> list = new ArrayList<>();
        //得到里面的图片
        for (ContentNode content : contents) {
            String type = content.getType();
            if ("image".equals(type)) {
                //就是图片,添加到list中
                list.add(content.getValue());
            }
            if (list.size() >= 3) {
                break;
            }
        }
        dtoSave.setImages(list);
    }


}

























